package cn.sylinx.hbatis.ext.function;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.ServiceLoader;

public class FunctionFactory {

	private final Map<String, IFunction> registers = new HashMap<String, IFunction>();

	private static final FunctionFactory instance = new FunctionFactory();

	public static FunctionFactory get() {
		return instance;
	}

	private FunctionFactory() {
		registerDefaultFunctions();
	}

	/**
	 * 注册函数
	 */
	private void registerDefaultFunctions() {

		ServiceLoader<IFunction> sl = ServiceLoader.load(IFunction.class);
		if (sl != null) {
			Iterator<IFunction> funit = sl.iterator();
			while (funit.hasNext()) {
				register(funit.next());
			}
		}
	}

	public IFunction getFunction(String alias) {
		return registers.get(alias);
	}

	/**
	 * 注册函数
	 * 
	 * @param f
	 */
	public void register(IFunction f) {
		registers.put(f.sqlAlias(), f);
	}

}
